package cn.dglydrpy.study.algorithm.od;

/**
 * @author Yyy
 * @date 2024/11/10 16:17
 * @description
 * 输入单向链表，输出其中倒数第 k 个结点，链表倒数第 1 个结点为尾指针
 */
public class Od0036_LastedKeyInLInked {
    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);
        
        int k =2;
        Node node = myAnswer(head,k);
        System.out.println(node.value);
    }

    private static Node myAnswer(Node head, int k) {

        Node temp = head;
        
        while (k>0){
            temp = temp.next;
            k--;
        }

        while (temp.next != null){
            temp = temp.next;
            head = head.next;
        }
        
        return head.next;
        
    }

    private static class Node{
        private int value;
        private Node next;
        
        public Node(int value){
            this.value = value;
        }
    }
}
